package com.itechart.watchfacts.dao.orm;

import com.itechart.watchfacts.dao.GeneralDAO;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: E.Krasnotschek
 * Date: 7/23/13
 * Time: 7:59 AM
 * To change this template use File | Settings | File Templates.
 */
public abstract class HibernateGeneralDAO<T> implements GeneralDAO<T>{

    protected Class< T > clazz;

    @Autowired
    protected SessionFactory sessionFactory;

    @Override
    public final void setClazz( Class< T > clazzToSet ){
        this.clazz = clazzToSet;
    }

    @Override
    public void create(T entry) {
        sessionFactory.getCurrentSession().save(entry);
    }

    @Override
    public void delete(int id) {
        T entry = (T) sessionFactory.getCurrentSession().load(
                clazz, id);
        if (null != entry) {
            sessionFactory.getCurrentSession().delete(entry);
        }
    }


    @Override
    public List<T> list() {
        return sessionFactory.getCurrentSession().createQuery( "from " + clazz.getName() ).list();
    }
}
